import org.molamil.acto.core.Logger;

import mx.xpath.XPathAPI;

import org.molamil.acto.params.ParamContext;
import org.molamil.acto.props.PropsParser;
import org.molamil.commons.StringUtil;
import org.molamil.acto.core.ParserError;

/**
 * @author Jorge Hernandez
 */
class org.molamil.acto.params.ParamsParser {
	
	
	// Constants
	
	public static var ERROR_DUPLICATE_NAME:String = "ERROR: Duplicate param name: \"{name}\".";
	
	
	// Properties
	
	private static var log:Logger = Logger.getLogger("ParamParser");
	
	
	// Functions
	
	//TODO: Test.	//TODO: Add default value.
	public static function parse(xml:XML):Array {
		
		log.info("parse()");
		
		xml.ignoreWhite = true;
		
		// Create the object.
		var a:Array = new Array();
		
		// Names holder.
		var names:Object = new Object();
		
		// Get nodes.
		var paramNodes:Array = XPathAPI.selectNodeList(xml.firstChild, "/" + xml.firstChild.nodeName + "/param");
		
		log.debug(paramNodes.length + " params found");
		
		for (var i:Number = 0; i < paramNodes.length; i++) {
			
			var paramNode:XMLNode = paramNodes[i];
			var param:ParamContext = new ParamContext();
			
			var name:String = paramNode.attributes["name"];
			if (names[name] != undefined) {
				var msg:String = StringUtil.replace(ERROR_DUPLICATE_NAME, "{name}", name);
				throw new ParserError(msg);
			}
			names[name] = true;
			
			param.name = name;
			param.isRequired = paramNode.attributes["required"].toLowerCase() == "true";
			
			var attrValidator:String = paramNode.attributes["validator"];
			if (attrValidator != null && attrValidator != "")				param.validators.push(attrValidator);
			
			param.props = PropsParser.parse(new XML(paramNode.toString()));
			
			a.push(param);
			
		}

		return a;
		
	}
	
	
}
